package com.wantup.remote.server;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/** 服务端，使用多线程一直开着Socket监听客户端连接
 * @author wangshangyi
 * @version V1.0  2020/8/14 11:17
 */
public class RPCServer {
    private final static int PORT = 8888;

    public static void main(String[] args) {
        try {
            ServerSocket server = new ServerSocket(PORT);
            while (true) {
               new ExecThread(server).start();
            }
        } catch (IOException ee) {
            ee.printStackTrace();
        }
    }
}

/**
 * 线程类，负责接收命令，执行操作
 */
class ExecThread extends Thread {
    Socket connection;
    DataInputStream in ;

    ExecThread(ServerSocket server) throws IOException {
        this.connection = server.accept();
        this.in = new DataInputStream(connection.getInputStream());
    }

    synchronized  void f(String s) {
        try {
            Runtime ec = Runtime.getRuntime();
            ec.exec(s);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void run() {
        System.out.println("接受线程启动");
        while (true) {
            try {
                String s = in.readUTF();
                f(s);//调用方法运行远程命令
                Thread.sleep(200);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

